# coding=utf-8
import json

import time

from django.db import transaction

from worldcup.apps.userModel.models import Comment, User
from worldcup.commons.CommonResult import rest, CommonResult


@transaction.atomic
@rest
def list_comment(request):
    openid = request.GET["openid"]
    comments = Comment.objects.filter(messaged_openid=openid, parentid=0).order_by("created_at").all()
    results = []

    for comment in comments:
        if comment.status == 1:
            comment.status = 2
            comment.save()
        results.append(CommentHelper().get_comment_tree(comment))
    return CommonResult(0, results)


@rest
def create_cmt(request):
    try:
        request_params = json.loads(request.body)
    except ValueError:
        return CommonResult(-1, "数据格式错误")
    openid = request_params["openid"]                        # 留言者
    user = User.objects.values("name", "imgurl").filter(openid=openid).get()
    messaged_openid = request_params["messagedOpenid"]       # 被留言者
    messaged_user = User.objects.values("name", "imgurl").filter(openid=messaged_openid).get()
    content = request_params["message"]
    try:
        parentid = request_params["parentid"]
        if parentid == "":
            parentid = 0
    except KeyError:
        parentid = 0
    timestamp = int(time.time())

    cmt = Comment(openid=openid, name=user['name'], img_url=user['imgurl'], messaged_openid=messaged_openid, messaged_name=messaged_user['name'],
                  messaged_img_url=messaged_user['imgurl'], content=content, parentid=int(parentid), created_at=timestamp, updated_at=timestamp)
    cmt.save()
    return CommonResult(0, "success")


class CommentTree(object):

    id = -1

    def __init__(self, id, openid, name, img_url, messaged_openid, messaged_name, messaged_img_url, content, created_at, updated_at, parentid, children):
        self.id = id
        self.openid = openid
        self.name = name
        self.img_url = img_url
        self.messaged_openid = messaged_openid
        self.messaged_name = messaged_name
        self.messaged_img_url = messaged_img_url
        self.content = content
        self.created_at = created_at
        self.updated_at = updated_at
        self.parent_id = parentid
        self.children = children

    def to_dict(self):
        return {
            "id": self.id,
            "openid": self.openid,
            "name": self.name,
            "imgUrl": self.img_url,
            "messagedOpenid": self.messaged_openid,
            "messagedName": self.messaged_name,
            "messagedImgUrl": self.messaged_img_url,
            "content": self.content,
            "createdAt": self.created_at,
            "updatedAt": self.updated_at,
            "parentId": self.parent_id,
            "children": self.children
        }


class CommentHelper(object):

    def get_comment_tree(self, comment):
        return self.__get_tree(comment)

    def __get_tree(self, comment):
        root_dict = CommentTree(comment.id, comment.openid, comment.name, comment.img_url, comment.messaged_openid, comment.messaged_name, comment.messaged_img_url, comment.content, comment.created_at, comment.updated_at,
                            comment.parentid, []).to_dict()
        self.__add_tree(root_dict)
        return root_dict

    def __add_tree(self, parent):
        comments = Comment.objects.filter(parentid=parent["id"]).order_by("created_at").all()
        for comment in comments:
            if comment.status == 1:
                comment.status = 2
                comment.save()
            comment_tree_dict = CommentTree(comment.id, comment.openid, comment.name, comment.img_url, comment.messaged_openid,comment.messaged_name, comment.messaged_img_url, comment.content, comment.created_at,
                                       comment.updated_at, comment.parentid, []).to_dict()
            parent["children"].append(comment_tree_dict)
            self.__add_tree(comment_tree_dict)



